# -*- coding: utf-8 -*-
# todo.views

import logging
import simplejson

from werkzeug import (
    unescape, redirect, Response,
)

from kay.utils import render_to_response
from kay.handlers import BaseHandler

from todo.models import Todo

def index(request):
  return render_to_response('todo/index.html')

def todos(request):
    '''get the entire list of todos in json. Used by REST API of Todo Collection'''
    items = Todo.all().order('order').fetch(100)
    data = []
    for item in items:
        data.append(item.to_dict())
    return Response(simplejson.dumps(data), content_type='application/json')

class TodoHandler(BaseHandler):
    '''Handler for the Backbone Todo model REST APIs'''
    def get(self, id):
        '''Select todo, not used in application'''
        todo = Todo.get_by_id(id)
        return Response(todo.to_json(), content_type='application/json')

    def put(self, id):
        '''Update todo'''
        model = simplejson.loads(self.request.data)
        todo = Todo.get_by_id(id)
        todo.content = model['content']
        todo.done = model['done']
        todo.put()
        data = {'success': True, 'msg': 'Todo updated'}
        return Response(simplejson.dumps(data), content_type='application/json')

    def post(self, id=None):
        '''Create new todo, return the newly created todo in json'''
        model = simplejson.loads(self.request.data)
        todo = Todo(content=model['content'], done=model['done'], order=model['order'])
        todo.put()
        # return the newly created instance
        return Response(todo.to_json(), content_type='application/json')

    def delete(self, id):
        '''Delete Todo by id'''
        todo = Todo.get_by_id(id)
        todo.delete()
        data = {'success': True, 'msg': 'Todo deleted'}
        return Response(simplejson.dumps(data), content_type='application/json')
